



const path = require('path')
const fileUtil = require('./fileUtil')


exports.getSysPkg = function () {
    const sysPkgPath = '../../../package.json'
    return require(sysPkgPath)
}



exports.getPkgByAsarPath = function (asarPath) {
    const pkgPath = path.join(asarPath, "plugin.json")
    return require(pkgPath)
}

exports.getPkgByPluginPath = function (pluginPath) {
    const pkgPath = path.join(pluginPath, "plugin.json")
    return require(pkgPath)
}




exports.mergeBasePreloadJsFile = function (thePkgPath, type) {
    const theFolder = path.dirname(thePkgPath)
    let pkg = exports.getPkgByAsarPath(theFolder)
    const preloadPath = pkg.preload

    let thePath
    let preloadExitst = true
    if (preloadPath == null) {
        thePath = path.join(theFolder, "preload.js")
        preloadExitst = false
    } else {
        thePath = path.join(theFolder, preloadPath)
    }
    const preloadJs = fileUtil.openFile(fileUtil.getMainPreloadJsPath())
    const beforeContent = fileUtil.openFile(thePath)
    let newPreload
    if (type == "merge") {
        newPreload = beforeContent + '\n//------以下为运行时依赖，勿删------\n' + preloadJs
        fileUtil.writeFile(thePath, newPreload)

    } else {
        if (!preloadExitst) {
            // 恢复preload.js
            fileUtil.rmFile(thePath)
            // 恢复pkg
            pkg.preload = null
            fileUtil.writeFile(thePkgPath, JSON.stringify(pkg, null, 4))
        } else {
            newPreload = beforeContent.replace('\n//------以下为运行时依赖，勿删------\n' + preloadJs, "")
            fileUtil.writeFile(thePath, newPreload)
        }
    }
}

